var fs = require('fs');
var express = require('express');
var router = express.Router();
var student = require('./model/student');

//初始化
router.get('/index',function(req,res){
  student.init(function(err,students){
    if(err){
      return res.status(500).send('err');
    }
    res.render('index.html',{
      students:students
    });
  })
})

router.post('/students/new',function(req,res){
  student.add(req.body,function(err){
    if(err){
      return res.status(500).send('err')
    }
    res.redirect(302,'/index')
  })
})

router.get('/new',function(req,res){
  res.render('new.html')
})

router.get('/edit',function(req,res){
  var id = req.query.id;
  student.initnew(id,function(err,data){
    if(err){
      return res.status(500).send('err')
    }
    res.render('newedit.html',{
      students:data
    })
  })
})

router.post('/students/newedit',function(req,res){
  student.updata(req.body,function(err){
    if(err){
      return res.status(500).send('err')
    }
    res.redirect(302,'/index');
  })
})

router.get('/delete',function(req,res){
  var id = req.query.id;
  student.delete(id,function(err){
    console.log(err)
    if(err){
      return res.status(500).send('err')
    }
    res.redirect(301,'/index');
  })
})

router.get('/seach',function(req,res){
  var keyWord = req.query.keyWord
  student.seach(keyWord,function(err,e){
    if(err){
      res.status(500).send('err')
    }
    res.render('index.html',{
      students:e
    })
  })
})

module.exports = router;